<template>
	<view class="base-page-white">
		<view class="">
			<u--form labelPosition="left" labelWidth="100" :model="contract" :rules="rules" ref="uForm">
				<view class="page_conten_title">
					<view class="yangsf-m-l-20">{{prompt+`信息`}}</view>
				</view>
				<view class="yangsf-padding-lr-20">
					<u-form-item :label="prompt+'姓名'" prop="userName" borderBottom ref="item1">
						<u--input v-model="contract.userName" inputAlign="right" border="none"
							:placeholder="prompt+'姓名'" @input="userNameTrim" clearable></u--input>
					</u-form-item>
					<u-form-item label="身份证号" prop="userCardNo" borderBottom ref="item1">
						<u--input v-model="contract.userCardNo" inputAlign="right" border="none"
							:placeholder="prompt+`身份证号`" @input="userCardNoTrim" clearable></u--input>
					</u-form-item>
					<!-- <u-form-item label="联系电话" prop="userTele" borderBottom ref="item1">
						<u--input v-model="contract.userTele" inputAlign="right" border="none"
							:placeholder="prompt+'联系电话'" @input="userTeleTrim" clearable></u--input>
					</u-form-item> -->
				</view>

				<view class="page_conten_title">
					<view class="yangsf-m-l-20">借款信息</view>
				</view>
				<view class="yangsf-padding-lr-20">
					<u-form-item label="借款金额" prop="money" borderBottom ref="item1">
						<u--input v-model="contract.money" type="number" inputAlign="right" border="none"
							placeholder="请输入借款金额" clearable @change="compute"></u--input>
					</u-form-item>
					<u-form-item label=" 年化利率" prop="moneyRate" borderBottom ref="item1">
						<u--input v-model="contract.moneyRate" type="number" inputAlign="right" border="none"
							placeholder="请输入年化利率" suffixIcon="%" @change="compute"></u--input>
					</u-form-item>
					<u-form-item label="是否分期" prop="isTag" borderBottom ref="item1">
						<view class="sw_class">
							<u-switch v-model="isTag" @change="change"></u-switch>
						</view>
					</u-form-item>
					<u-form-item v-if="isTag" label="还款期数" prop="stages" borderBottom ref="item1">
						<!-- <u--input type="select" v-model="contract.stages" border="none" inputAlign="right"
							placeholder="请选择还款期数" @change="compute" clearable></u--input> -->

						<!-- <u-picker :show="show" :columns="list"></u-picker> -->
						<!-- <u-action-sheet :actions="list" title="分期数" :show="show"></u-action-sheet> -->

						<view class="sw_class">
							<u-number-box v-model="contract.stages" :min="3" :max="12" :step="3"
								@change="compute"></u-number-box>
						</view>
					</u-form-item>

					<u-form-item v-if="" :label="isTag?'每月还款日':'还款日'" prop="repayment" borderBottom ref="item1"
						@click="selectDate">
						<u-datetime-picker :show="showData" mode="date" @confirm="confirmData"
							:minDate="Number(new Date().getTime() + 24 * 60 * 60 * 1000)"
							@cancel="cancelDate"></u-datetime-picker>
						<u-picker :show="showNum" :columns="columns" @confirm="confirmNum" @cancel="close"
							@close="close"></u-picker>
						<u--input v-model="contract.repayment" inputAlign="right" border="none"
							:placeholder="isTag?'每月还款日':'还款日'" @change="compute" :suffixIcon="isTag?'日':''"
							readonly></u--input>
					</u-form-item>
					<!-- <u-form-item v-else label="还款日" prop="repayment" borderBottom ref="item1" @click="showData=true">
						
						<u--input v-model="contract.repayment" border="none" inputAlign="right" placeholder="请输入还款日"
							@change="compute" clearable></u--input>
					</u-form-item> -->
				</view>
				<view class="page_conten_title yangsf-flex-justify-content-space-between">
					<view class="yangsf-m-l-20">还款总金额(等额本息)</view>
					<view class="yangsf-m-r-20">{{contract.totalMoney}}</view>
				</view>
				<view class="yangsf-padding-lr-20">
					<u-form-item label="合同备注" prop="remark" borderBottom ref="item1">
						<u--textarea v-model="contract.remark" placeholder="合同备注" readonly></u--textarea>
					</u-form-item>
				</view>
			</u--form>
		</view>

		<view class="yangsf-page-bottom-button yangsf-card">
			<view class="yangsf-ratio-w-80">
				<u-button type="primary" text="发起合同" @click="save"></u-button>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		getUserInfo,
		saveContract
	} from '@/config/api.js'
	export default {
		data() {
			return {
				showNum: false,
				showData: false,
				isTag: false,
				prompt: '借款人',
				member: {},
				show: false,
				columns: [
					[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
						28, 29, 30
					]
				],
				list: [{
						value: 3,
						name: '3期'
					},
					{
						value: 6,
						name: '6期'
					},
					{
						value: 9,
						name: '9期'
					},
					{
						value: 12,
						name: '12期'
					},
				],
				contract: {
					debtor: '',
					debtorCardNo: '',
					debtorTele: '',
					money: '',
					moneyRate: '',
					kind: '',
					stages: ''
				},
				rules: {
					'userName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userCardNo': [{
							type: 'string',
							required: true,
							message: '请填写身份证号',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								return uni.$u.test.idCard(value);
							},
							message: '身份证号不符合规则',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								console.log("this.member.idCard ==> {}", this.member.idCard);
								console.log("输入的证件号 ==> {}", value);
								console.log("比较一下 ==> {}", this.member.idCard == value);
								return this.member.idCard == value ? false : true;
							},
							// validator: this.checkIdCardNo(rule, value, callback),
							message: '不能填写自己的证件号',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'userTele': [{
							type: 'string',
							required: true,
							message: '请填写联系电话',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'money': {
						type: 'string',
						required: true,
						message: '请填写借款金额',
						trigger: ['blur', 'change']
					},
					'moneyRate': {
						type: 'string',
						required: true,
						message: '请填写年化利率',
						trigger: ['blur', 'change']
					},

					'repayment': {
						type: 'string',
						required: true,
						message: '请填写还款日',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onLoad(opthon) {
			console.log("opthon ==> {}", opthon);
			//1.出借人 0.借款人
			this.contract.kind = opthon.kind
			if (this.contract.kind == 1) {
				this.prompt = '借款方';
			} else {
				this.prompt = '出借方';
			}

			this.getUserMsg()
		},
		methods: {
			getUserMsg() {
				getUserInfo().then(res => {
					this.member = res.data
				})
			},
			compute() {
				console.log("计算总还款金额");

				console.log("借款金额：{}， 利率：{}，是否分期：{}", this.contract.money, this.contract.moneyRate, this.contract.isTag);
				if (this.contract.money) {
					if (this.contract.moneyRate) {
						//是否分期：1.不分期按照 0.分期
						if (this.contract.isTag == 1) {
							console.log("计算总还款金额 ==> 分期");
							const r = this.contract.moneyRate / 100 / 12;
							const n = this.contract.stages;
							const monthlyPayment = this.contract.money * r * Math.pow(1 + r, n) / (Math.pow(1 + r, n) -
								1);
							const totalPayment = monthlyPayment * n;
							this.contract.totalMoney = Math.round(totalPayment * 100) / 100;
						} else {
							console.log("计算总还款金额 ==> 不分期");
							if (this.contract.repayment) {
								const startDate = new Date(); // 当前时间作为借款起始日
								const endDate = new Date(this.contract.repayment);
								// 如果还款日期小于当前日期，抛出错误
								if (endDate < startDate) {
									throw new Error("还款日期不能早于今天");
								}
								// 计算天数差
								const diffInTime = endDate.getTime() - startDate.getTime();
								const diffInDays = Math.ceil(diffInTime / (1000 * 3600 * 24));
								console.log("使用时长: {}", diffInDays);

								// 计算利息和总还款金额
								const interest = this.contract.money * (this.contract.moneyRate / 100) * (diffInDays /
									365);
								console.log("总利息: {}", interest);
								const totalRepayment = parseInt(this.contract.money) + parseFloat(interest);
								console.log("还款总额: {}", totalRepayment);
								this.contract.totalMoney = Math.round(totalRepayment * 100) / 100;
								this.contract.stages = 1;
							}
						}
					} else {
						this.contract.totalMoney = this.contract.money
					}
				}
			},
			save() {
				this.$refs.uForm.validate().then(res => {
					// uni.$u.toast('校验通过')
					saveContract(this.contract).then(res => {
						console.log("提交成功");
						if (res.code == 200) {
							uni.$u.route({
								type: 'reLaunch',
								url: 'pages/contract/fx',
								params: {
									id: res.data.id,
									debtor: res.data.debtor,
									money: res.data.money,
									moneyRate: res.data.moneyRate
								}
							})
						} else {
							uni.$u.toast(res.msg)
						}
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})

			},
			change(e) {
				console.log('change', e);
				this.contract.repayment = ''
				this.contract.totalMoney = ''
				this.isTag = e
				this.contract.isTag = 0
				this.contract.stages = 1
				if (e) {
					this.contract.isTag = 1
					this.contract.stages = 3
				}
				this.compute()
			},
			formatDate(timestamp) {
				const date = new Date(timestamp); // 创建 Date 对象
				const year = date.getFullYear(); // 年份
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要 +1
				const day = String(date.getDate()).padStart(2, '0'); // 日期

				return `${year}-${month}-${day}`;
			},
			selectDate() {
				if (this.isTag) {
					this.showNum = true
				} else {
					this.showData = true
				}
			},
			confirmData(e) {
				console.log("选择日期 ==> {}, {}", e.value, e.mode);
				console.log("转换日期 ==> {}", uni.$u.date(e.value, 'yyyy-mm-dd'));
				this.contract.repayment = uni.$u.date(e.value, 'yyyy-mm-dd')
				this.$refs.uForm.validateField('repayment')
				this.cancelDate()
				this.compute()
			},
			cancelDate() {
				this.showData = false
			},
			confirmNum(e) {
				this.contract.repayment = e.value[0]
				this.$refs.uForm.validateField('repayment')
				this.close()
			},
			close() {
				this.showNum = false
			},
			userNameTrim(event) {
				this.contract.userName = event.detail.value.trim();
			},
			userCardNoTrim() {
				this.contract.userCardNo = event.detail.value.trim();
			},
			userTeleTrim() {
				this.contract.userTele = event.detail.value.trim();
			}
		}
	}
</script>

<style scoped>
	.sw_class {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
</style>